package com.ug.managent.service.impl;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.ug.common.config.RuoYiConfig;
import com.ug.common.core.redis.RedisCache;
import com.ug.common.utils.DateUtils;
import com.ug.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metrics;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import com.ug.managent.mapper.CoverMapper;
import com.ug.managent.domain.Cover;
import com.ug.managent.service.ICoverService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 井盖档案Service业务层处理
 * 
 * @author Leo
 * @date 2025-04-22
 */
@Service
public class CoverServiceImpl implements ICoverService
{
    private static final Logger log = LoggerFactory.getLogger(CoverServiceImpl.class);

    private static final String CACHE_COVER_KEY = "cache:cover";

    private static int DISTANCE = 1;

    @Autowired
    private CoverMapper coverMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    RedisCache redisCache;

    public static final String EXCHANGE_DIRECT = "exchange.direct.cover";
    public static final String ROUTING_KEY = "cover";

    /**
     * 查询井盖档案
     * 
     * @param id 井盖档案主键
     * @return 井盖档案
     */
    @Override
    public Cover selectCoverById(Long id)
    {
        return coverMapper.selectCoverById(id);
    }

    /**
     * 查询井盖档案列表
     * 
     * @param cover 井盖档案
     * @return 井盖档案
     */
    @Override
    public List<Cover> selectCoverList(Cover cover)
    {
        List<Cover> list = coverMapper.selectCoverList(cover);
        for(Cover cover1 : list){
            redisCache.setGEO(CACHE_COVER_KEY,Double.parseDouble(cover1.getLongitude().toString()),
                    Double.parseDouble(cover1.getLatitude().toString()),cover1.getId().intValue());
            redisCache.expire(CACHE_COVER_KEY, 60*60, TimeUnit.SECONDS);
        }
        return list;
    }

    /**
     * 新增井盖档案
     * 
     * @param cover 井盖档案
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCover(Cover cover)
    {
        int id;
        GeoResults<RedisGeoCommands.GeoLocation<Integer>> geoResults = redisCache.getNear(CACHE_COVER_KEY,Double.parseDouble(cover.getLongitude().toString()),
                Double.parseDouble(cover.getLatitude().toString()),DISTANCE, Metrics.NEUTRAL);

        List<Integer> list1 = new ArrayList<>();
        geoResults.forEach(geoResult -> {
            RedisGeoCommands.GeoLocation<Integer> location = geoResult.getContent();
            list1.add(location.getName());
        });

        if(list1.isEmpty()){
            cover.setCreateBy(SecurityUtils.getUserId().toString());
            cover.setCreateTime(DateUtils.getNowDate());
            coverMapper.insertCover(cover);
            id = Math.toIntExact(cover.getId());
        }else{
            id = list1.get(0);
            cover.setId((long) id);
            cover.setUpdateTime(DateUtils.getNowDate());
            cover.setUpdateBy(SecurityUtils.getUserId().toString());
            coverMapper.updateCover(cover);
        }

        // 拼接URL
        String url = cover.getImage();
        int last = url.lastIndexOf('/');
        String project = url.substring(0, last);
        String sub = url.substring(last + 1);
        String[] list = sub.split("\\.");
        String name = String.valueOf(id);
        String newUrl = project + "/" + name +  "." + list[1];

        Path originalPath = Paths.get(url.replace("/profile", RuoYiConfig.getProfile()));
        Path targetPath = Paths.get(newUrl.replace("/profile", RuoYiConfig.getProfile()));

        // 重命名文件
        try {
            Files.move(originalPath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }

        cover.setImage(newUrl);
        coverMapper.updateCover(cover);

        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, ROUTING_KEY, project);

        return id;
    }

    /**
     * 修改井盖档案
     * 
     * @param cover 井盖档案
     * @return 结果
     */
    @Override
    public int updateCover(Cover cover)
    {
        cover.setUpdateTime(DateUtils.getNowDate());
        redisCache.deleteObject(CACHE_COVER_KEY+":"+cover.getId());
        return coverMapper.updateCover(cover);
    }

    /**
     * 批量删除井盖档案
     * 
     * @param ids 需要删除的井盖档案主键
     * @return 结果
     */
    @Override
    public int deleteCoverByIds(Long[] ids)
    {
        return coverMapper.deleteCoverByIds(ids);
    }

    /**
     * 删除井盖档案信息
     * 
     * @param id 井盖档案主键
     * @return 结果
     */
    @Override
    public int deleteCoverById(Long id)
    {
        return coverMapper.deleteCoverById(id);
    }
}
